// 模拟炒股交易云函数
const cloud = require('wx-server-sdk')

cloud.init({
  env: 'cloud1-8g3kxnyv58f85f9b'
})

const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const { action, ...params } = event

  try {
    switch (action) {
      case 'buy':
        return await buyStock(wxContext.OPENID, params)
      case 'sell':
        return await sellStock(wxContext.OPENID, params)
      case 'getPositions':
        return await getPositions(wxContext.OPENID)
      case 'getOrders':
        return await getOrders(wxContext.OPENID)
      default:
        return {
          success: false,
          error: 'invalid_action',
          message: '无效的操作类型'
        }
    }
  } catch (error) {
    console.error('模拟交易云函数执行失败:', error)
    return {
      success: false,
      error: 'function_failed',
      message: '操作失败，请重试',
      details: error.message
    }
  }
}

// 买入股票
async function buyStock(openid, { stockCode, stockName, shares, price }) {
  const transaction = await db.startTransaction()

  try {
    const amount = shares * price

    // 检查账户资金 - 修复查询条件
    const accountResult = await transaction.collection('simulation_accounts').where({
      _openid: openid
    }).get()

    console.log('查询账户结果:', accountResult)
    console.log('openid:', openid)

    if (accountResult.data.length === 0) {
      // 如果按_openid查询不到，尝试按openid字段查询
      const accountResult2 = await transaction.collection('simulation_accounts').where({
        openid: openid
      }).get()

      console.log('按openid字段查询结果:', accountResult2)

      if (accountResult2.data.length === 0) {
        throw new Error('账户不存在，请先初始化账户')
      }

      // 使用第二次查询的结果
      accountResult.data = accountResult2.data
    }

    const account = accountResult.data[0]
    if (account.availableCash < amount) {
      throw new Error('资金不足')
    }

    // 创建订单
    const orderResult = await transaction.collection('simulation_orders').add({
      data: {
        openid: openid,  // 添加openid字段
        orderType: 'buy',
        stockCode: stockCode,
        stockName: stockName,
        shares: shares,
        price: price,
        amount: amount,
        status: 'filled',
        createTime: db.serverDate(),
        fillTime: db.serverDate()
      }
    })

    // 更新或创建持仓
    let positionResult = await transaction.collection('simulation_positions').where({
      _openid: openid,
      stockCode: stockCode
    }).get()

    // 如果按_openid查询不到，尝试按openid查询
    if (positionResult.data.length === 0) {
      positionResult = await transaction.collection('simulation_positions').where({
        openid: openid,
        stockCode: stockCode
      }).get()
    }

    if (positionResult.data.length > 0) {
      // 更新现有持仓
      const position = positionResult.data[0]
      const newShares = position.shares + shares
      const newTotalCost = position.totalCost + amount
      const newAvgPrice = newTotalCost / newShares

      await transaction.collection('simulation_positions').doc(position._id).update({
        data: {
          shares: newShares,
          availableShares: newShares,
          avgPrice: newAvgPrice,
          totalCost: newTotalCost,
          updateTime: db.serverDate()
        }
      })
    } else {
      // 创建新持仓
      await transaction.collection('simulation_positions').add({
        data: {
          openid: openid,  // 添加openid字段
          stockCode: stockCode,
          stockName: stockName,
          shares: shares,
          availableShares: shares,
          avgPrice: price,
          totalCost: amount,
          currentPrice: price,
          marketValue: amount,
          profit: 0,
          profitRate: 0,
          createTime: db.serverDate(),
          updateTime: db.serverDate()
        }
      })
    }

    // 更新账户资金
    await transaction.collection('simulation_accounts').doc(account._id).update({
      data: {
        availableCash: _.inc(-amount),
        updateTime: db.serverDate()
      }
    })

    await transaction.commit()

    return {
      success: true,
      message: '买入成功',
      orderId: orderResult._id
    }

  } catch (error) {
    await transaction.rollback()
    console.error('买入失败:', error)
    return {
      success: false,
      error: 'buy_failed',
      message: error.message || '买入失败'
    }
  }
}

// 卖出股票
async function sellStock(openid, { stockCode, shares, price }) {
  const transaction = await db.startTransaction()

  try {
    const amount = shares * price

    // 检查持仓 - 修复查询条件
    let positionResult = await transaction.collection('simulation_positions').where({
      _openid: openid,
      stockCode: stockCode
    }).get()

    if (positionResult.data.length === 0) {
      // 尝试按openid字段查询
      positionResult = await transaction.collection('simulation_positions').where({
        openid: openid,
        stockCode: stockCode
      }).get()

      if (positionResult.data.length === 0) {
        throw new Error('无持仓')
      }
    }

    const position = positionResult.data[0]
    if (position.availableShares < shares) {
      throw new Error('持仓不足')
    }

    // 创建订单
    const orderResult = await transaction.collection('simulation_orders').add({
      data: {
        openid: openid,  // 添加openid字段
        orderType: 'sell',
        stockCode: stockCode,
        stockName: position.stockName,
        shares: shares,
        price: price,
        amount: amount,
        status: 'filled',
        createTime: db.serverDate(),
        fillTime: db.serverDate()
      }
    })

    // 更新持仓
    const newShares = position.shares - shares
    if (newShares <= 0) {
      // 清仓
      await transaction.collection('simulation_positions').doc(position._id).remove()
    } else {
      // 减少持仓
      const newTotalCost = position.avgPrice * newShares

      await transaction.collection('simulation_positions').doc(position._id).update({
        data: {
          shares: newShares,
          availableShares: newShares,
          totalCost: newTotalCost,
          updateTime: db.serverDate()
        }
      })
    }

    // 更新账户资金 - 修复查询条件
    let updateResult = await transaction.collection('simulation_accounts').where({
      _openid: openid
    }).update({
      data: {
        availableCash: _.inc(amount),
        updateTime: db.serverDate()
      }
    })

    // 如果按_openid更新失败，尝试按openid更新
    if (updateResult.stats.updated === 0) {
      await transaction.collection('simulation_accounts').where({
        openid: openid
      }).update({
        data: {
          availableCash: _.inc(amount),
          updateTime: db.serverDate()
        }
      })
    }

    await transaction.commit()

    return {
      success: true,
      message: '卖出成功',
      orderId: orderResult._id
    }

  } catch (error) {
    await transaction.rollback()
    console.error('卖出失败:', error)
    return {
      success: false,
      error: 'sell_failed',
      message: error.message || '卖出失败'
    }
  }
}

// 获取持仓
async function getPositions(openid) {
  try {
    // 先按_openid查询
    let result = await db.collection('simulation_positions').where({
      _openid: openid
    }).orderBy('createTime', 'desc').get()

    // 如果按_openid查询不到，尝试按openid字段查询
    if (result.data.length === 0) {
      result = await db.collection('simulation_positions').where({
        openid: openid
      }).orderBy('createTime', 'desc').get()
    }

    return {
      success: true,
      positions: result.data
    }
  } catch (error) {
    console.error('获取持仓失败:', error)
    throw error
  }
}

// 获取订单
async function getOrders(openid) {
  try {
    // 先按_openid查询
    let result = await db.collection('simulation_orders').where({
      _openid: openid
    }).orderBy('createTime', 'desc').limit(20).get()

    // 如果按_openid查询不到，尝试按openid字段查询
    if (result.data.length === 0) {
      result = await db.collection('simulation_orders').where({
        openid: openid
      }).orderBy('createTime', 'desc').limit(20).get()
    }

    return {
      success: true,
      orders: result.data
    }
  } catch (error) {
    console.error('获取订单失败:', error)
    throw error
  }
}
